<template>
  <div class="addOrgUnit">
    <div class="infoContent">
      <el-row :gutter="1">
        <el-col :offset="1" :span="22">
          <el-form
            ref="form"
            :disabled="addOrgUnitObj.addOrgUnitType == 2"
            :model="orgUnitInfo"
            :rules="rules"
            label-width="150px"
          >
            <template v-if="addOrgUnitObj.addOrgUnitType != 3">
              <el-form-item label="基本信息" />
              <el-form-item label="组织单元名称:" prop="name">
                <el-input v-model="orgUnitInfo.name" />
              </el-form-item>
              <el-form-item label="备注:">
                <el-input v-model="orgUnitInfo.description" />
              </el-form-item>
              <el-form-item label="选择组织" />
            </template>
            <el-form-item label="组织定位:">
              <el-input v-model="target" placeholder="输入组织编码/名称定位组织" />
            </el-form-item>
            <el-form-item label>
              <!-- <organization-tree
                ref="unitTree"
                node-key="phid"
                :filter-node-method="filterNode"
                :data="treeData"
                show-checkbox
                :check-strictly="true"
                :props="{ label: 'name' }"
                :selected-ids="orgUnitInfo.orgIds"
              /> -->
              <!-- :render-content="treeRender" -->
              <el-tree
                ref="unitTree"
                :key="treeKey"
                :filter-node-method="filterNode"
                :data="treeData"
                :props="{ label: 'name' }"
                :default-checked-keys="orgUnitInfo.orgIds"
                node-key="phid"
                show-checkbox
              />
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </div>
    <p v-if="addOrgUnitObj.addOrgUnitType != 2" class="stepCon">
      <span class="greenBtn" @click="$emit('update:addOrgUnitShow',false)">取消</span>
      <span class="greenBtn" @click="save">保存</span>
    </p>
  </div>
</template>
<script>
import { addOrgGroup, updateOrgGroup, findOneByOrgGroupId, getOrgTreeList, getOrgUsedList } from '@/api/organization'

export default {
  name: 'AddOrgUnit',
  components: {
    // 'organization-tree': OrganizationTree
  },
  props: {
    addOrgUnitShow: {
      type: Boolean,
      default: false
    },
    addOrgUnitObj: {
      type: Object,
      default() {
        return {
          addOrgUnitType: 0,
          parentId: '',
          orgList: [],
          defaultList: [],
          detail: null
        }
      }
    }
  },
  data() {
    return {
      treeData: [],
      defaultCheckedKey: [],
      target: '',
      rules: {
        name: [
          { required: true, message: '请填写组织单元名称', trigger: 'blur' }
        ]
      },
      treeKey: Math.random(),
      orgUnitInfo: {
        description: '', // (string, optional): 描述 ,
        levels: '', // (integer, optional): 层次 ,
        name: '', // (string, optional): 名称 ,
        orgIds: [], // (Array[integer], optional): 组织id集合 ,
        parentId: '' // (integer, optional): 父级id
      }
    }
  },
  watch: {
    target(val) {
      this.$refs.unitTree.filter(val)
    }
  },
  created() {
    this.addOrgUnitObj.orgList.forEach(
      i => {
        i.disabled =
          !!i.orgTypeId && i.orgTypeId !== this.addOrgUnitObj.detail.phid
      }
    )
    if (this.addOrgUnitObj.addOrgUnitType !== 2) {
      this.orgUnitInfo.parentId = this.addOrgUnitObj.parentId
    } else {
      this.addOrgUnitObj.orgList.forEach(i => (i.disabled = true))
    }
    if (this.addOrgUnitObj.addOrgUnitType !== 0) {
      // console.log('!= 0')
      this.defaultCheckedKey = this.addOrgUnitObj.defaultList
      this.orgUnitInfo = JSON.parse(JSON.stringify(this.addOrgUnitObj.detail))
    }
    this.getOrgUsedList().then(select => {
      this.getOrgTreeList(select)
    })
    this.handleGetOrgGroupDetail()
  },
  inject: ['getOrgList', 'getOrgTypeList'],
  mounted() {},
  methods: {
    treeRender(h, { node, data, store }) {
      return <span>{data.encode + data.name}</span>
    },
    save() {
      this.$refs.form.validate(valid => {
        if (valid) {
          var params = this.orgUnitInfo
          params.orgIds = this.$refs.unitTree.getCheckedKeys()

          if (this.addOrgUnitObj.addOrgUnitType === 1 || this.addOrgUnitObj.addOrgUnitType === 3) {
            updateOrgGroup(params)
              .then(res => {
                if (res.status) {
                  this.$msgBox.show('修改组织单元成功！')
                  this.$emit('update:addOrgUnitShow', false)
                  this.$emit('refresh')
                } else {
                  this.$msgBox.error(res.message)
                }
              })
              .catch(err => {
                console.log(err)
                this.$msgBox.error('修改组织单元失败！')
              })
            return
          }
          addOrgGroup(params)
            .then(res => {
              if (res.status) {
                this.$msgBox.show('新增组织单元成功！')
                this.$emit('update:addOrgUnitShow', false)
                this.$emit('refresh')
              } else {
                this.$msgBox.error(res.message)
              }
            })
            .catch(err => {
              console.log(err)
              this.$msgBox.error('新增组织单元失败！')
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 获取组织树
    getOrgTreeList(selectedUnit) {
      getOrgTreeList().then(res => {
        if (res.status) {
          const setChecked = arr => arr.forEach(v => {
            selectedUnit.includes(v.phid) && (v.disabled = true)
            v.children && v.children.length && setChecked(v.children)
          })
          setChecked(res.data)
          this.treeData = res.data || []
          this.treeKey = Math.random()
        } else {
          this.$msgBox.error(res.message)
        }
      }).catch(err => {
        console.log(err)
        this.$msgBox.error('获取组织列表失败！')
      })
    },
    // 获取已经使用组织
    getOrgUsedList() {
      return getOrgUsedList().then(res => {
        return res.data
      })
    },
    handleGetOrgGroupDetail() {
      findOneByOrgGroupId(this.addOrgUnitObj.detail.phid).then(res => {
        this.orgUnitInfo.orgIds = res.data.children.map(v => v.phid)
        this.treeKey = Math.random()
      }).catch(() => {
        this.$msgBox.error('获取组织单元详情失败')
      })
    },
    // getSelectedIdFromTree(tree) {
    //   const selectedIds = []

    // },
    checkTreeChange(item, newVal, sonVal) {
      var phidlist = []
      function getPhid(list) {
        list.forEach(item => {
          if (!item.disabled) {
            phidlist.push(item.phid)
          }
          if (item.children && item.children.length) {
            getPhid(item.children)
          }
        })
      }
      if (item.children && item.children.length) {
        getPhid(item.children)
        var arr = this.$refs.unitTree.getCheckedKeys()
        if (newVal) {
          this.$refs.unitTree.setCheckedKeys(
            [...new Set(arr.concat(phidlist))],
            true
          )
        } else {
          this.$refs.unitTree.setCheckedKeys(
            arr.filter(i => !phidlist.includes(i)),
            false
          )
        }
      }
    },
    filterNode(value, data) {
      if (!value) return true
      return data.name.includes(value) || data.encode.includes(value)
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/styles/variables.scss';
.addOrgUnit {
  font-size: 0.16rem;
  height: 600px;
  overflow: auto;
  // position: relative;
  .infoType {
    height: 30px;
    line-height: 30px;
    background: #f1f1f1;
    > li {
      float: left;
      height: 100%;
      width: 80px;
      cursor: pointer;
      text-align: center;
      &.active {
        background: #fff;
        cursor: default;
        color: #2e91ff;
      }
    }
  }
  .infoContent {
    padding: 20px 20px 40px;
  }
  .registrationInfo {
    text-align: center;
    > li {
      margin: 0 auto;
      display: inline-block;
      overflow: visible;
      height: 40px;
      line-height: 40px;
      margin-bottom: 10px;
      > div {
        float: left;
        width: 75px;
        text-align: right;
        margin-right: 30px;
        &:nth-of-type(2) {
          float: left;
          width: 700px;
          > div {
            float: left;
            width: 300px;
            > div {
              width: 300px;
            }
            &:last-of-type {
              float: right;
              width: 380px;
              > div {
                width: 75px;
                display: inline-block;
                &:last-of-type {
                  width: 300px;
                }
              }
            }
          }
        }
      }
      .longW {
        width: 700px;
        > div {
          width: 700px !important;
        }
      }
    }
  }
  .attechment {
    height: 410px;
  }
  .stepCon {
    text-align: right;
    color: #19A0E8;
    bottom: 0;
    right: 20px;
    z-index: 99;
    width: 100%;
    background: #fff;
    position: absolute;
    padding: 10px 20px 20px 0;
    span {
      cursor: pointer;
      margin-left: 20px;
    }
  }
  li.red-line {
    height: 1px;
    background: red;
    margin: 0 92px 13px 60px;
    display: block;
  }
  li.imgUpload {
    height: auto;
    .longW > div > div {
      width: auto;
    }
  }
}
.warningColor {
  color: $pink;
}
</style>
<style>
.addRegist .el-date-editor .el-range-separator {
  width: 20px;
}
</style>

